package cn.hughie.imooc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author yuh
 * @Date Created in 下午10:21 2018/5/25
 * @Description
 */
public class CounterBoolean {

    private static final int threadNum = 100;
    private static final int totalClient = 5000;
    //可以用于isInit
    private static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void count() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadNum);
        CountDownLatch latch = new CountDownLatch(totalClient);
        for (int i = 0; i < totalClient; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                test();
                latch.countDown();
                semaphore.release();
            });
        }
        latch.await();
        executorService.shutdown();
    }


    public static void test() {
        if (atomicBoolean.compareAndSet(false, true)) {
            System.out.println("execute");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        count();
    }
}
